#pragma once

using namespace System;
using namespace System::Runtime::InteropServices;

#define VPX_CODEC_DISABLE_COMPAT 1
#include<vpx\vpx_decoder.h>
#include<vpx\vp8dx.h>
#define decInterface (vpx_codec_vp8_dx())

#include"Image.h"
#include"Common.h"

namespace NVP8 
{
	public ref class Decoder
	{
	public:
		Decoder()
		{
			codec = new vpx_codec_ctx_t();
			iter = new vpx_codec_iter_t();
		}
		
		void Init()
		{
			int res = vpx_codec_dec_init(codec, decInterface, NULL, 0);
			ThrowOnError(res, codec, "Failed to initialize decoder");
		}

		bool Decode(array<Byte>^ encodedData, int offset, int length)
		{
			*iter = NULL;
			pin_ptr<unsigned char> data = &encodedData[offset];
			int result = vpx_codec_decode(codec, data, length, NULL, 0);
			if (result != 0)
			{
				const char* error = vpx_codec_error(codec);
				const char* errorDetail = vpx_codec_error_detail(codec);
				return false;
			}
			return true;
		}

		bool GetNextFrame(VPXImage^ decodedImage)
		{
			vpx_image_t* image;
			if ((image = vpx_codec_get_frame(codec, iter)))
			{
				decodedImage->Init(image);
				return true;
			}
			return false;
		}

		!Decoder()
		{
			vpx_codec_destroy(codec);
			delete codec;
			delete iter;
		}

		~Decoder()
		{
			this->!Decoder();
		}

	private:
		vpx_codec_ctx_t* codec;
		vpx_codec_iter_t* iter;
	};
}
